package ordinaryArray;

import org.junit.Test;

import java.util.Arrays;

/*
 *@description 分发糖果
 *@author hkfan
 *@version 1.0
 *@create 2025/5/27 10:53
 */
public class LeetCode_135 {

    @Test
    public void test(){
        System.out.println(candy(new int[]{1,2,87,87,87,2,1}));
    }


    public int candy(int[] ratings) {
        //0. 特殊情况
        if (ratings.length==0){
            return 0;
        } else if (ratings.length==1) {
            return 1;
        } else if (ratings.length==2) {
            if (ratings[0]==ratings[1]){
                return 2;
            }else {
                return 3;
            }
        }
        //1. 定义
        int[] res = new int[ratings.length];
        //2. 初始化
        Arrays.fill(res,1);
        //3. 遍历
        for (int i = 0; i < ratings.length; i++) {
            if (i==0){  //左边界
                if (ratings[i]>ratings[i+1]){
                    res[i]=res[i+1]+1;
                } else if (ratings[i]<ratings[i+1]) {
                    res[i+1]=res[i]+1;
                }
            } else if (i< ratings.length-1) {   //中间
                if (ratings[i-1]>ratings[i]){   //左侧
                    res[i-1]=Math.max(res[i-1], res[i]+1);
                    check(ratings,res,i);
                } else if (ratings[i-1]<ratings[i]) {
                    res[i]=Math.max(res[i-1]+1, res[i]);
                }
                if (ratings[i+1]>ratings[i]){   //右侧
                    res[i+1]=Math.max(res[i+1], res[i]+1);
                } else if (ratings[i+1]<ratings[i]) {
                    res[i]=Math.max(res[i+1]+1, res[i]);
                    check(ratings,res,i);
                }
            }else {     //右边界
                if (ratings[i-1]>ratings[i]){
                    res[i-1]=Math.max(res[i-1], res[i]+1);
                    check(ratings,res,i);
                } else if (ratings[i-1]<ratings[i]) {
                    res[i]=Math.max(res[i-1]+1, res[i]);
                }
            }
        }
        //4. 返回结果
        int sum = 0;
        for (int re : res) {
            sum+=re;
        }
        return sum;
    }

    private void check(int[] ratings, int[] res, int index) {
        int i = index;
        while (i>=1 && ratings[i]<ratings[i-1]){
            if (res[i]==res[i-1]){
                res[i-1]++;
                i--;
            }else{
                break;
            }
        }
    }


}
